#include "webenginetab.h"
#include "ui_webenginetab.h"

#include <QWebEngineProfile>
#include <webenginepage.h>
#include <widget.h>

WebEngineTab::WebEngineTab(QWidget *parent) :
    QTabWidget(parent),
    ui(new Ui::WebEngineTab)
{
    ui->setupUi(this);
}

WebEngineTab::~WebEngineTab()
{
    delete ui;
}

void WebEngineTab::createTab(const QString &url)
{
    Widget *widget = new Widget(url, this);
    connect(widget->getPage()->profile(), &QWebEngineProfile::downloadRequested, this, &WebEngineTab::downloadRequested);

    connect(widget->getPage(), &QWebEnginePage::windowCloseRequested, this, [ = ]()
    {
//        sender()
        removeTab(currentIndex());
    });
    connect(widget, &Widget::titleUpdate, this, [ = ]()
    {
        Widget *widget = (Widget *)sender();
        setTabText(indexOf(widget), widget->getPage()->title());
    });
    addTab(widget, "加载中...");
    setCurrentWidget(widget);
}

QWebEnginePage *WebEngineTab::getPage()
{
    Widget *widget = (Widget *)currentWidget();
    if (widget)
    {
        return widget->getPage();
    }
    return nullptr;
}

void WebEngineTab::goBack()
{
    Widget *widget = (Widget *)currentWidget();
    if (widget)
    {
        widget->goBack();
    }
}

void WebEngineTab::goForward()
{
    Widget *widget = (Widget *)currentWidget();
    if (widget)
    {
        widget->goForward();
    }
}

void WebEngineTab::refresh()
{
    Widget *widget = (Widget *)currentWidget();
    if (widget)
    {
        widget->refresh();
    }
}
